<template>
  <view class="settlement-container">
    <!-- 地址选择卡片 -->
    <view class="settlement-container2">
      <view class="card address-card" @click="selectAddress">
        <view class="card-header">
          <text>配送地址:</text>
        </view>
        <view class="card-content">
          <text>{{ selectedAddress ? (selectedAddress.name + '（' + selectedAddress.phone + '）') : '' }}</text>
          <text>{{ selectedAddress ? (selectedAddress.address_line1 + ' ' + selectedAddress.address_line2) : '请选择地址' }}</text>
        </view>
      </view>

      <!-- 商品信息卡片 -->
      <view class="card">
        <view class="card-header">
          <text>商品信息</text>
        </view>
        <view class="card-content">
          <view v-if="passedCartItem" class="product-item">
            <image :src="passedCartItem.img" class="product-image"></image>
            <view class="product-info">
              <text class="product-name">{{ passedCartItem.name }}</text>
              <view class="product-price-quantity">
                <text class="product-price">￥{{ formatPrice((passedCartItem.discount_price || passedCartItem.original_price) * passedCartItem.quantity) }}</text>
                <text class="product-quantity">x{{ passedCartItem.quantity }}</text>
              </view>
            </view>
          </view>
          <!-- 会员折扣 -->
          <view class="membership-discount" v-if="membershipDiscount > 0">
            <text>会员折扣:</text>
            <text class="discount-value">{{ membershipDiscount }}折</text>
          </view>
          <view class="membership-discount">
            <text>运费:</text>
            <text class="discount-value">￥{{ formatPrice(shippingCost) }}</text>
          </view>
        </view>
      </view>

      <!-- 运费和留言卡片 -->
      <view class="card">
        <view class="card-header">
          <text>留言:</text>
        </view>
        <view class="card-content">
          <input v-model="message" type="text" placeholder="请输入留言（最多30字）" maxlength="30" />
        </view>
      </view>
    </view>

    <!-- 合计和提交订单固定条 -->
    <view class="total-section">
      <view class="total-amount">
        <text>合计:</text>
        <text class="amount-value">￥{{ formatPrice(totalAmount) }}</text>
      </view>
      <view class="submit-order">
        <button @click="showPaymentMethods">提交订单</button>
      </view>
    </view>

    <!-- 支付方式弹窗 -->
    <view class="payment-methods" v-if="showPaymentMethodsDialog" @click="closePaymentMethodsDialog">
      <view class="payment-methods-content" @click.stop>
        <button @click="payWithWechat" class="payment-button">微信支付</button>
        <button @click="payWithAlipay" class="payment-button">支付宝支付</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedAddress: null,
      cartItems: [],
      passedCartItem: {}, // 用于存储从本地存储中获取的单个商品数据
      shippingCost: 0,
      message: '',
      totalAmount: 0,
      showPaymentMethodsDialog: false,
      membershipDiscount: 0, // 新增会员折扣
    };
  },
  onLoad(options) {
    // 从本地存储中获取缓存的商品数据
    const cachedProductData = uni.getStorageSync('cachedProductData');
    if (cachedProductData) {
      this.passedCartItem = cachedProductData;
      this.calculateTotal(); // 计算总价
    } else {
      // 如果没有缓存数据，可以提示用户或进行其他操作
      uni.showToast({
        title: '未找到缓存的商品数据',
        icon: 'none'
      });
    }
    this.fetchSelectedAddress(); // 获取选中的地址
  },
  onShow() {
    this.fetchUserInfo();
  },
  methods: {
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address2/address2'
      });
    },
    fetchSelectedAddress() {
      const selectedAddressId = uni.getStorageSync('selectedAddressId');
      if (selectedAddressId) {
        const token = uni.getStorageSync('Authorization');
        const url = `http://localhost:8887/Useraddress/select?id=${selectedAddressId}`;
        const header = {
          'Authorization': token,
        };
        uni.request({
          url,
          method: 'GET',
          header,
          success: (res) => {
            if (res.data.success) {
              this.selectedAddress = res.data.data;
            } else {
              uni.showToast({
                title: '获取地址信息失败',
                icon: 'none',
              });
            }
          },
          fail: () => {
            uni.showToast({
              title: '请求失败',
              icon: 'none',
            });
          },
        });
      }
    },
    fetchUserInfo() {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/user/userInfo';
      const header = {
        'Authorization': token
      };
      uni.request({
        url,
        method: 'GET',
        header,
        success: (res) => {
          if (res.data.code === 200 && res.data.success) {
            this.membershipDiscount = parseFloat(res.data.data.discount); // 存储会员折扣
            this.calculateTotal(); // 重新计算总价
          }
        },
        fail: () => {
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      });
    },
    calculateTotal() {
      // 确保 passedCartItem 存在且包含必要的数据
      if (this.passedCartItem && this.passedCartItem.quantity) {
        let total = 0;
        const price = parseFloat(this.passedCartItem.discount_price || this.passedCartItem.original_price);
        total = price * parseInt(this.passedCartItem.quantity, 10);
        total += this.shippingCost; // 加上运费
        // 应用会员折扣
        if (this.membershipDiscount > 0) {
          total = total * (this.membershipDiscount / 100);
        }
        this.totalAmount = parseFloat(total).toFixed(2);
      } else {
        this.totalAmount = 0;
      }
    },
    formatPrice(value) {
      return parseFloat(value).toFixed(2);
    },
    showPaymentMethods() {
      this.showPaymentMethodsDialog = true;
    },
    closePaymentMethodsDialog() {
      this.showPaymentMethodsDialog = false;
    },
    payWithWechat() {
      this.processPayment('微信支付');
    },
    payWithAlipay() {
      this.processPayment('支付宝支付');
    },
    processPayment(paymentMethod) {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Order/oneadd';
      const orderData = {
        useraddress_id: this.selectedAddress.id,
        total_amount: this.totalAmount,
        payment_method: paymentMethod,
        message: this.message,
		discount:this.membershipDiscount,
        orderProducts: [{
            product_id: this.passedCartItem.id,
            quantity: this.passedCartItem.quantity,
            discount_price: this.passedCartItem.discount_price,
            original_price: this.passedCartItem.original_price
        }]
      };
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json'
      };
      uni.request({
        url,
        method: 'POST',
        header,
        data: orderData,
        success: (res) => {
            if (res.data.success) {
                uni.showToast({
                    title: '支付成功',
                    icon: 'success'
                });
                console.log(res.data.data); // 打印返回的订单数据
                const orderId = res.data.data.id; // 假设返回的数据中包含 orderId
                this.goToOrderDetails(orderId); // 跳转到订单详情页面
            } else {
                uni.showToast({
                    title: '支付失败',
                    icon: 'none'
                });
                this.closePaymentMethodsDialog();
            }
        },
        fail: () => {
            uni.showToast({
                title: '请求失败',
                icon: 'none'
            });
            this.closePaymentMethodsDialog();
        }
      });
    },
    goToOrderDetails(orderId) {
        uni.navigateTo({
            url: `/pages/orderdetails/orderdetails?id=${orderId}`
        });
    },
  }
}
</script>

<style>
  .settlement-container {
    position: relative;
    padding: 15px;
  }

  .settlement-container2 {
    padding-bottom: 200px;
    /* 留出空间给底部支付栏 */
  }

  .card {
    background-color: #f9f9f9;
    border: 1px solid #eaeaea;
    margin-bottom: 20rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }

  .card-header {
    font-size: 32rpx;
   font-weight: bold;
   margin-bottom: 20rpx;
   }
   
   .card-content {
   font-size: 28rpx;
   color: #555;
   display: flex;
   flex-direction: column;
   }
   
   .address-card .card-content {
   flex-direction: column;
   }
   
   .product-item {
   display: flex;
   align-items: center;
   margin-bottom: 10px;
   }
   
   .product-image {
   width: 60px;
   height: 60px;
   margin-right: 10px;
   }
   
   .product-info {
   flex: 1;
   display: flex;
   flex-direction: column;
   }
   
   .product-name {
   font-size: 28rpx;
   color: #333;
   white-space: normal;
   word-break: break-word;
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;
   }
   
   .product-price-quantity {
   display: flex;
   justify-content: space-between;
   }
   
   .product-price {
   color: #ff9966;
   font-size: 30rpx;
   }
   
   .product-quantity {
   font-size: 24rpx;
   color: #888;
   }
   
   .card-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 20rpx;
   }
   
   .shipping-cost {
   font-size: 28rpx;
   color: #555;
   }
   
   .cost-value {
   font-size: 30rpx;
   color: #ff9966;
   }
   
   .buyer-message input {
   border: 1px solid #eee;
   padding: 10px;
   border-radius: 4px;
   width: 100%;
   font-size: 28rpx;
   }
   
   .total-section {
   position: fixed;
   bottom: 0;
   left: 0;
   right: 0;
   background-color: white;
   padding: 20rpx;
   box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
   display: flex;
   justify-content: space-between;
   align-items: center;
   z-index: 1000;
   /* 确保在弹窗之上 */
   }
   
   .total-amount {
   font-size: 32rpx;
   color: #333;
   }
   
   .amount-value {
   font-size: 36rpx;
   color: #ff9966;
   }
   
   .submit-order button {
   background-color: #ff9966;
   color: white;
   border: none;
   padding: 10px;
   width: 100%;
   }
   
   .payment-methods {
   position: fixed;
   left: 0;
   right: 0;
   bottom: 0;
   top: 0;
   background-color: rgba(0, 0, 0, 0.6);
   display: flex;
   justify-content: flex-end;
   align-items: flex-end;
   z-index: 1001;
   }
   
   .payment-methods-content {
   display: flex;
   flex-direction: row;
   justify-content: center;
   background-color: white;
   padding: 10px;
   width: 100%;
   box-sizing: border-box;
   /* margin-bottom: 20px; /
   / 距离底部的距离 /
   border-top: 1px solid #eee;
   / 去除圆角，添加边框 */
   }
   
   .payment-methods-content .payment-button {
   flex: 1;
   height: 80rpx;
   background-color: #ff9966;
   color: white;
   border: none;
   font-size: 28rpx;
   margin: 0 10px;
   border-top: 1px solid #eee;
   /* 分割线 */
   }
   
   /* 新增会员折扣样式 */
   .membership-discount {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 10px;
   font-size: 28rpx;
   color: #555;
   }
   
   .discount-value {
   color: #ff9966;
   font-size: 30rpx;
   }
   </style> 